package com.rdiot.yx485.ui.bind

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.databinding.ObservableField
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.drake.net.utils.TipUtils
import com.king.zxing.util.LogUtils
import com.lindroy.iosdialog.IAlertDialog
import com.rdiot.yx485.R
import com.rdiot.yx485.base.BaseFragment
import com.rdiot.yx485.base.BindModelFactory
import com.rdiot.yx485.base.LocalData
import com.rdiot.yx485.databinding.FraEnterRoomInfoBinding
import com.rdiot.yx485.ui.bind.model.BindViewModel
import com.rdiot.yx485.util.RoomUtils
import com.rdiot.yx485.util.askPermission
import com.rdiot.yx485.util.goToAppSetting
import com.rdiot.yx485.util.setClickLimitListener
import java.util.concurrent.atomic.AtomicBoolean


/**
 * 输入房间信息页
 * @author mR2hao
 * @date 2022/11/21
 */
class EnterRoomInfoFragment : BaseFragment<FraEnterRoomInfoBinding>() {
    override fun getLayoutId() = R.layout.fra_enter_room_info
    private var dialog: IAlertDialog? = null
    private var isShowingDialog = AtomicBoolean(false)

    private val bindViewModel: BindViewModel by activityViewModels { BindModelFactory() }


    private val resultLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == Activity.RESULT_OK) {
                val scan = result.data?.getStringExtra("SCAN_RESULT")
                bindViewModel.panelNum.set(scan)
                LogUtils.i("扫描结果：$scan")
            }
        }

    private fun openScanner() {
        resultLauncher.launch(Intent(context, QRCodeActivity::class.java))
    }

    override fun initView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ) {
        binding.vm = bindViewModel
        binding.familyData = LocalData.familyData.value
        if (bindViewModel.isBindInfrared) {
            bindViewModel.panelNum=  ObservableField("ESP_GATTS_DEMO")
        }
        binding.btnNext.setClickLimitListener {
            if (bindViewModel.roomName.get().isNullOrBlank()
                || bindViewModel.panelNum.get().isNullOrBlank()
            ) {
                TipUtils.toast(getString(R.string.please_enter_info_correctly))
                return@setClickLimitListener
            }

            if (bindViewModel.isBindSub) {
                findNavController().navigate(R.id.action_enterRoomInfoFragment_to_bindFragment)
            } else {
                findNavController().navigate(R.id.action_enterRoomInfoFragment_to_enterWifiInfoFragment)
            }

        }

        binding.ivScan.setClickLimitListener {
            if (LocalData.firstCamera) {
                showHint()
            }else {
                askPermission()
            }
        }

    }

    private fun askPermission() {
        act.askPermission(false) { allGranted: Boolean?, deniedList: MutableList<String>? ->
            LogUtils.e("allGranted:$allGranted - $deniedList")

            if (allGranted == true) {
                openScanner()
            } else {
                if (!isShowingDialog.getAndSet(true)) {
                    showNeedPermissionDialog(allGranted)
                }
            }
        }
    }

    private fun showHint() {
        LocalData.firstCamera = false
        dialog?.dismiss()
        dialog = IAlertDialog.build(this)
            .setTitle("相机权限使用说明")
            .setMessage("用于拍照、录制视频、扫描二维码等场景")
            .setNegButtonText(R.string.cancel)
            .setCancelOutside(false)
            .setNegClickListener {
                return@setNegClickListener
            }
            .setAlpha(1.0F)
//            .setPosButtonText(R.string.go_setting)
            .setPosClickListener {
                askPermission()
            }
        dialog?.show()
    }

    private fun showNeedPermissionDialog(allGranted: Boolean?) {
        if (dialog?.isVisible != true) {
            dialog?.dismiss()
            dialog = IAlertDialog.build(this)
                .setTitle(R.string.hint)
                .setMessage(R.string.need_allow_pic)
                .setNegButtonText(R.string.cancel)
                .setCancelOutside(false)
                .setNegClickListener {
                    isShowingDialog.set(false)
                }
                .setAlpha(1.0F)
                .setPosButtonText(R.string.go_setting)
                .setPosClickListener {
                    if (allGranted == null) {
                        act.goToAppSetting(true)

                    } else if (allGranted != true) {
                        askPermission()
                    }
                    isShowingDialog.set(false)
                }
            dialog?.show()
        }
    }

    override fun onResume() {
        super.onResume()
        (act as BindActivity).setNBTitle(getString(R.string.add_room))
    }

}

